import { Button, Input, Select, Switch, Slider, message } from 'antd'  // 添加message导入
import { useEffect, useState } from 'react'
import { generateUUID } from '@/utils'
import { useSourceOptions } from '@/pages/workflow/hooks/use-source-options'
import { CommmonSmallJudgmentCommon } from '@/pages/workflow/components/CommonSmallTemp'
import { debounce } from 'lodash';  // 导入debounce函数
import Editor, { loader } from '@monaco-editor/react'
import  {stringOperatorOptions,numberOperatorOptions,arrayOperatorOptions,objectOperatorOptions} from '../../../constants'

const InputCont = ({ info, editData }) => {
  const { options } = useSourceOptions(info)
  const [loopVars, setLoopVars] = useState([])
  const [conditions, setConditions] = useState([])
  const [filterOptions,setFilterOptions] = useState(options)
  const filterOpertaions = {
    "string":stringOperatorOptions ,
    "number":[
     ...numberOperatorOptions,
     ...objectOperatorOptions
    ],
    "object":objectOperatorOptions,
    "array_string":arrayOperatorOptions,
    "array_number":arrayOperatorOptions,
    "array_object":objectOperatorOptions,
  }

  const VARIABLE_TYPES = [
    { value: 'string', label: 'String' },
    { value: 'number', label: 'Number' },
    { value: 'object', label: 'Object' },
    { value: 'array_string', label: 'Array[Srting]' },
    { value: 'array_number', label: 'Array[Number]' },
    { value: 'array_object', label: 'Array[Object]' }
  ]

  const VARIABLE_PLACEHOLDERS = {
    array_string: '["字符串1", "字符串2"]',
    array_number: '[1, 2, 3]',
    array_object: '[{"key": "value"}, {"key": "value"}]',
    object: '{"key": "value"}',
    string: '输入文本'
  }
  

  useEffect(() => {
    if (Array.isArray(info.inputList) && info.inputList.length > 0) {
      setLoopVars(info.inputList)
    }
    if (Array.isArray(info.filter.rules) && info.filter.rules.length > 0) {
      setConditions(info.filter.rules)
    }
  }, [info])

  const addLoopVar = () => {
    const newVar = {
      id: generateUUID(8),
      variable: '',
      variableType: undefined,  // 修改这里，添加 varType 字段
      type: 'cite',
      value: ''
    }
    const newVars = [...loopVars, newVar]
    setLoopVars(newVars)
    editData({ ...info, inputList: newVars })
  }

  const removeLoopVar = (id) => {
    const newVars = loopVars.filter(v => v.id !== id)
    setLoopVars(newVars)
    editData({ ...info, inputList: newVars })
  }

  const addCondition = () => {
    const newCondition = {
      id: generateUUID(8),
      type: 'cite',
      operation: '',  // 操作符
      valueType: 'constant',  // 值类型：常量/引用
      value: '',  // 输入值
      inputType: 'cite'  // 条件类型：引用
    }
    const newConditions = [...conditions, newCondition]
    setConditions(newConditions)
    editData({ ...info, filter:{
      ...info.filter,
      rules: newConditions} })
  }

  const removeCondition = (id) => {
    const newConditions = conditions.filter(c => c.id !== id)
    setConditions(newConditions)
    editData({ ...info, filter:{
      ...info.filter,
      rules: newConditions} })
  }

  const renderSection = (title, enabled, onSwitch, children) => (
    <div className="mb-4">
      <div className="flex items-center justify-between mb-2">
        <span className="text-sm font-bold">{title}</span>
        <Switch size="small" checked={enabled} onChange={onSwitch} />
      </div>
      {enabled && children}
    </div>
  )

  return (
    <div className="px-[5px] pt-[2px]">
      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-bold">循环变量</span>
          <Button 
            type="dashed"
            onClick={addLoopVar}
            className="h-[24px] min-w-[24px] flex items-center justify-center p-0 w-[80px] mt-2"
          >
            + 添加变量
          </Button>
        </div>
        <div className="flex flex-wrap gap-2">
          {loopVars.map((variable) => (
            <div key={variable.id} className="flex flex-col gap-2 p-2 border border-gray-200 rounded">
              <div className="flex items-center gap-2">
                <Input
                  placeholder="变量名"
                  value={variable.variable}
                  onChange={(e) => {
                    const newVars = loopVars.map(v => 
                      v.id === variable.id ? { ...v, variable: e.target.value } : v
                    )
                    setLoopVars(newVars)
                    editData({ ...info, inputList: newVars })
                  }}
                  style={{ width: 140 }}
                />
                <Select
                  value={variable.variableType}
                  onChange={(value) => {
                    const newVars = loopVars.map(v => 
                      v.id === variable.id ? { ...v, variableType: value,value:'',valuet:'' } : v
                    )

                    setLoopVars(newVars)
                    // 清空终止条件中引用该变量的值
                    const updatedConditions = conditions.map(c => {
                      if (c.type === 'cite' && c.variable ===  `${info.id},${variable.variable}`) {
                        return { ...c, value: '',valuet: '', sourceType: value, operation:''  }
                      }
                      return c
                    })
                    setConditions(updatedConditions)
                    editData({ 
                      ...info, 
                      inputList: newVars,
                      filter: {
                        ...info.filter,
                        rules: updatedConditions
                      }
                    })
                  }}
                  style={{ width: 140 }}
                  placeholder="变量类型"
                  options={VARIABLE_TYPES}
                />
                <Select
                  value={variable.type}
                  onChange={(value) => {
                    const newVars = loopVars.map(v => 
                      v.id === variable.id ? { ...v, type: value, value: '', valuet:'' } : v
                    )
                    setLoopVars(newVars)
                    editData({ ...info, inputList: newVars })
                  }}
                  style={{ width: 90 }}
                  placeholder="输入模式"
                  options={[
                    { value: 'constant', label: '常量' },
                    { value: 'cite', label: '引用' }
                  ]}
                />
                <svg viewBox="0 0 1024 1024" width="18" height="18" fill="currentColor" onClick={() => removeLoopVar(variable.id)} className='cursor-pointer text-red-500'>
                  <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"/>
                </svg>
              </div>
              <div className="flex items-center gap-2">
                {variable.type === 'cite' ? (
                  <CommmonSmallJudgmentCommon
                    item={variable}
                    optionList={loopVars}
                    options={options.map(option => ({
                      ...option,
                      options: variable.variableType ? option.options?.filter(opt => opt.sourceType?.startsWith(variable.variableType)) : option.options
                    })).filter(option => option.options?.length > 0)}
                    i={loopVars.findIndex(v => v.id === variable.id)}
                    Change={(newList) => {
                      setLoopVars(newList)
                      editData({ ...info, inputList: newList })
                    }}
                    className="w-[387px]"
                  />
                ) : (
                  ['object', 'array_string', 'array_number', 'array_object'].includes(variable.variableType) ? (
                    <div>
                      <Editor
                        height="100px"
                        width="387px"
                        language="json"
                        theme="vs-light"
                        value={variable.value}
                        onChange={(value) => {
                          const newVars = loopVars.map(v => 
                            v.id === variable.id ? { ...v, value, valuet: value } : v
                          )
                          setLoopVars(newVars)
                          editData({ ...info, inputList: newVars })
                        }}
                        onValidate={(markers) => {
                          if (markers.length > 0) {
                            const newVars = loopVars.map(v => 
                              v.id === variable.id ? { ...v, error: '格式不正确' } : v
                            )
                            setLoopVars(newVars)
                          } else {
                            const newVars = loopVars.map(v => 
                              v.id === variable.id ? { ...v, error: '' } : v
                            )
                            setLoopVars(newVars)
                          }
                        }}
                        options={{
                          lineNumbers: 'off',
                          minimap: { enabled: false },
                          scrollBeyondLastLine: false,
                          automaticLayout: true,
                        }}
                      />
                    </div>
                  ) : (
                    <Input
                      placeholder="输入值"
                      value={variable.value}
                      onChange={(e) => {
                        const newVars = loopVars.map(v => 
                          v.id === variable.id ? { ...v, value: e.target.value,valuet: e.target.value } : v
                        )
                        setLoopVars(newVars)
                        editData({ ...info, inputList: newVars })
                      }}
                      style={{ width: 387 }}
                    />
                  )
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-bold">循环终止条件</span>
          <Button 
              onClick={addCondition}
              className="h-[24px] flex items-center justify-center w-[80px] mt-2"
            >
              + 添加条件
          </Button>
        </div>
        <div className="flex gap-2">
          <div className="flex flex-col justify-center mr-1">
            {conditions.length >= 1 && (
              <div className="flex items-center gap-1 relative h-full">
                <Button
                  type="default"
                  size="small"
                  className="flex items-center justify-center gap-1 bg-blue-50 border-blue-100 w-[60px]"
                  onClick={() => editData({
                    ...info,
                    filter: {
                      ...info.filter,
                      logic: info.filter.logic === 'and' ? 'or' : 'and'
                    }
                  })}
                >
                  <span className="w-[32px] text-center">{info.filter.logic === 'and' ? 'AND' : 'OR'}</span>
                  <svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor">
                    <path d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm0 832a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm144.3-228.7L546.1 557.1V384h-68.3v215.9l143.5 143.5 34.7-34.8z"/>
                  </svg>
                </Button>
              </div>
            )}
          </div>
          <div className="flex-1 flex flex-col gap-2">
            {conditions.length >= 1 && <div className="relative pl-3">
              <div className="absolute -left-2 top-[10px] bottom-[10px] w-[6px] border-l-[1px] border-gray-400"></div>
              <div className="absolute -left-2 top-0 w-[6px] h-[10px] border-t-2 border-l-[1px] border-gray-400 rounded-tl"></div>
              <div className="absolute -left-2 bottom-0 w-[6px] h-[10px] border-b-2 border-l-[1px] border-gray-400 rounded-bl"></div>
              {conditions.map((condition) => (
                <div key={condition.id} className="flex flex-col gap-2 p-2 border border-gray-200 rounded">
                  <div className="flex items-center gap-2">
                    <CommmonSmallJudgmentCommon
                      item={condition}
                      optionList={conditions}
                      options={[{
                        title: 'iteration',
                        label: '循环 ',
                        key: 'loop',
                        options: loopVars.map(variable => ({
                          label: variable.variable,
                          value: `${info.id},${variable.variable}`,
                          sourceType: variable.variableType
                        }))
                      },...options]}
                      i={conditions.findIndex(c => c.id === condition.id)}
                      Change={(newList) => {
                        setConditions(newList)
                        editData({ ...info, filter: {
                          ...info.filter,
                          rules: newList
                        } })
                      }}
                      className="w-[200px]"
                      field='variable'
                    />
                    <Select
                      value={condition.operation}
                      onChange={(value) => {
                        const newConditions = conditions.map(c => 
                          c.id === condition.id ? { ...c, operation: value } : c
                        )
                        setConditions(newConditions)
                        editData({ ...info, filter: {
                          ...info.filter,
                          rules: newConditions
                        } })
                      }}
                      style={{ width: 90 }}
                      options={filterOpertaions[condition.sourceType]}
                    />
                    <svg 
                      viewBox="0 0 1024 1024" 
                      width="18" 
                      height="18" 
                      fill="currentColor"
                      className="cursor-pointer text-red-500 hover:text-red-600"
                      onClick={() => removeCondition(condition.id)}
                    >
                      <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"/>
                    </svg>
                  </div>
                  <div className="flex items-center gap-2">
                    {!['object', 'array_object'].includes(condition.sourceType) && (
                      <>
                        <Select
                          value={condition.valueType}
                          onChange={(value) => {
                            const newConditions = conditions.map(c => 
                              c.id === condition.id ? { ...c, valueType: value, value: '' } : c
                            )
                            setConditions(newConditions)
                            editData({ ...info, filter: {
                              ...info.filter,
                              rules: newConditions
                            } })
                          }}
                          style={{ width: 106 }}
                          options={['string', 'number'].includes(condition.sourceType) ? [
                            { value: 'constant', label: '常量' },
                            { value: 'cite', label: '引用' }
                          ] : [
                            { value: 'constant', label: '常量' }
                          ]}
                        />
                        {condition.valueType === 'cite' ? (
                          <CommmonSmallJudgmentCommon
                            item={condition}
                            optionList={conditions}
                            options={options.map(option => ({
                              ...option,
                              options: condition.sourceType ? option.options?.filter(opt => opt.sourceType?.startsWith(condition.sourceType)) : option.options
                            })).filter(option => option.options?.length > 0)}
                            i={conditions.findIndex(c => c.id === condition.id)}
                            Change={(newList) => {
                              setConditions(newList)
                              editData({ ...info, filter: {
                                ...info.filter,
                                rules: newList
                              } })
                            }}
                            className="w-[185px]"
                          />
                        ) : (
                          <Input
                            value={condition.value}
                            onChange={(e) => {
                              const newConditions = conditions.map(c => 
                                c.id === condition.id ? { ...c, value: e.target.value } : c
                              )
                              setConditions(newConditions)
                              editData({ ...info, filter: {
                                ...info.filter,
                                rules: newConditions
                              } })
                            }}
                            style={{ width: 185 }}
                          />
                        )}
                      </>
                    )}
                  </div>
                </div>
              ))}
            </div>}
          </div>
        </div>
      </div>

      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-bold">最大循环次数</span>
        </div>
        <div className="flex items-center gap-2">
          <Input
            className='w-[70px]'
            type="number"
            min={1}
            max={50}
            placeholder="请输入最大循环次数"
            value={info.max_loop_times}
            onChange={(e) => editData({
              ...info,
              max_loop_times: parseInt(e.target.value)
            })}
          />
          <Slider
            min={1}
            max={50}
            value={info.max_loop_times}
            onChange={(value) => editData({ ...info, max_loop_times: value })}
            tooltip={{ 
              formatter: (value) => `${value} 次`,
              placement: 'top'
            }}
            style={{ width: 387 }}
            styles={{
              track: { backgroundColor: '#8a2be2', height: 1 }, // 紫色，线宽1px
              rail: { backgroundColor: '#e6e6e6', height: 1 }, // 灰色，线宽1px
            }}
          />
        </div>
      </div>
    </div>
  )
}

export default InputCont